import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { MenuData } from '@/model/common/menu/model'
import { loadMenuByUser } from '@/api/common/menu/index'
import { StarRouterInfo, StarTabRouterType } from '@/model/common/tabMenu/model'

const homeRoute: Array<StarRouterInfo> = [
  {
    path: '/dashboard/base',
    routeIdx: 0,
    title: '首页',
    name: 'dashboard',
    isHome: true
  }
]

const useMenuStore = defineStore({
  id: 'star_menu',
  state: () => ({
    menuList: [] as MenuData[],
    tabRouterList: homeRoute,
    isRefreshing: false
  }),
  getters: {
    tabRouters: (state: StarTabRouterType) => state.tabRouterList,
    refreshing: (state: StarTabRouterType) => state.isRefreshing
  },
  actions: {
    async RESET_STATE () {
      this.$reset()
    },
    async getMenuList () {
      await loadMenuByUser().then((data) => {
        this.menuList = data
      }).catch(error => {
        ElMessage.error(error.message)
      })
    },
    // 刷新
    toggleTabRouterAlive (routeIdx: number) {
      this.isRefreshing = !this.isRefreshing
      this.tabRouters[routeIdx].isAlive = !this.tabRouters[routeIdx].isAlive
    },
    // 打开新增tab页
    appendTabRouterList (newRoute: StarRouterInfo) {
      // path拼接全路径
      newRoute.path = this.appendFullPath(newRoute.path, newRoute.query)

      if (!this.tabRouters.find((route: StarRouterInfo) => route.path === newRoute.path)) {
        this.tabRouterList = this.tabRouterList.concat({ ...newRoute, isAlive: true })
      } else if (this.tabRouters.find((route: StarRouterInfo) => route.path === newRoute.path && !this.compareQuery(route.query, newRoute.query))) {
        // path相同 query不同情况
        this.tabRouterList = this.tabRouterList.map((route: StarRouterInfo) => {
          return (route.path === newRoute.path && route.query !== newRoute.query) ? { ...newRoute, isAlive: true } : route
        })
      }
    },
    // 点击关闭按钮
    subtractCurrentTabRouter (newRoute: StarRouterInfo) {
      const { path } = newRoute
      if (path) {
        this.tabRouterList = this.tabRouterList.filter((tab) => tab.path !== path)
      }
    },
    // 关闭左侧
    subtractTabRouterLeft (newRoute: StarRouterInfo) {
      const { routeIdx } = newRoute
      // 大于0操作/去除首页
      if (routeIdx) {
        this.tabRouterList = homeRoute.concat(this.tabRouterList.slice(routeIdx))
      }
    },
    // 关闭右侧
    subtractTabRouterRight (newRoute: StarRouterInfo) {
      const { routeIdx } = newRoute
      if (routeIdx !== undefined) {
        this.tabRouterList = this.tabRouterList.slice(0, routeIdx + 1)
      }
    },
    // 关闭其他
    subtractTabRouterOther (newRoute: StarRouterInfo) {
      const { routeIdx } = newRoute
      if (routeIdx !== undefined) {
        this.tabRouterList = routeIdx === 0 ? homeRoute : homeRoute.concat([this.tabRouterList[routeIdx]])
      }
    },
    // 关闭所有
    subtractTabRouterAll () {
      this.tabRouterList = homeRoute
    },
    // 关闭当前页面
    closeCurrentPage (route: StarRouterInfo, router: any) {
      const tabs = this.tabRouters
      const query = route.query
      this.subtractCurrentTabRouter(route)

      if (query && query.fromPath && this.tabRouters.find((tab: StarRouterInfo) => tab.path === query.fromPath)) {
        const nextRoute = this.tabRouters.filter((row) => {
          return row.path === query.fromPath ? row : null
        })
        if (nextRoute) {
          router.push(nextRoute[0])
        }
      } else {
        tabs.forEach((tab, index) => {
          if (tab.path === route.path) {
            const nextTab = tabs[index + 1] || tabs[index - 1]
            if (nextTab) {
              router.push({ path: nextTab.path, query: nextTab.query })
            }
          }
        })
      }
    },
    compareQuery (query: any, newQuery: any) {
      if ((!query || Object.keys(query).length === 0) && (!newQuery || Object.keys(newQuery).length === 0)) {
        return true
      } else if ((query && !newQuery) || (!query && newQuery)) {
        return false
      }

      if (Object.keys(query).length !== Object.keys(newQuery).length) {
        return false
      }

      const keys: Array<string> = Object.keys(query)

      for (let i = 0; i < keys.length; i++) {
        const key = keys[i]
        if (newQuery[key] !== query[key]) {
          return false
        }
      }

      return true
    },
    appendFullPath (path: string, query: any) {
      // key使用path+query拼接，参数不一致打开新页面，后面如果只使用path判断，则直接返回path
      // if ((!query || Object.keys(query).length === 0)) {
      //   return path
      // }

      // const keys: Array<string> = Object.keys(query)

      // for (let i = 0; i < keys.length; i++) {
      //   const key = keys[i]
      //   path += path.indexOf('?') > 0 ? '&' : '?'
      //   path = path + key + '=' + query[key]
      // }

      return path
    }
  },
  persist: true
})

export default useMenuStore
